/*
 * 接口代理
 * @author li.xiaomei
 * @date 2016-12-15
 */

var request = require('request')
var utilMethod = require('../util/method.js')
var mockMiddle = require('./mock')

function isEmpty(obj) {
  if (obj == null) return true;

  if (obj.length > 0) return false;
  if (obj.length === 0) return true;

  for (var key in obj) {
    if (hasOwnProperty.call(obj, key)) return false;
  }
  return true;
}

module.exports = function(req, res, next){
  //如果是xhr请求，则代理转发该请求
  var orig = req.originalUrl;
  if(/^http:/.test(orig)) {
    var up = URL.parse(orig);
    orig = up.path;
  }

  var isProxy = utilMethod.findArgv('-o='),
      proxyHost = isProxy&&isProxy.split('=')[1] || global.think_config.proxy.host,
      apiUrl = proxyHost+orig;

  if(!isProxy) {
    console.log('【 没有设置proxy-进行本地数据mock 】'+ req.method + ': '+ apiUrl);
    mockMiddle(req, res, next);
    return false;
  }

  console.log('【数据接口转发】start '+ req.method + ': '+ apiUrl);

  request({
    method: req.method,
    url: apiUrl,
    qs: req.query,
    form: req.body,
    headers: {
      'Cookie': req.headers.cookie
    }
  }, function(err, agentRes){

    if(err||agentRes.statusCode==404||!agentRes.body||(JSON.parse(agentRes.body) && JSON.parse(agentRes.body).ec!=200)) {
      console.log('接口转发失败：\n'+
                  'statusCode:' + (agentRes && agentRes.statusCode||0) +'\n' +
                  '内容body:' + (agentRes && agentRes.body||0) +'\n' + 
                  '进行【本地数据mock】start ');

      mockMiddle(req, res, next);
      return;
    }

    //将远程返回的headers的field转发给客户端
    if(agentRes.headers){
      for(var field in agentRes.headers) {
        res.append(field, agentRes.headers[field]);
      }
    }

    if(isEmpty(agentRes.body)){
      res.send(agentRes.text);
    }else {
      res.send(agentRes.body);
    }

  });
 }
